package day10.threadLocal.example;

import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 
 * 〈一句话功能简述〉<br>
 * 
 * 
 * @author heshishan
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class ThreadMsgHoldContext {

    static final ThreadLocal<ThreadBean> threadLocal = new InheritableThreadLocal<ThreadBean>();
    private static final AtomicLong nextSerialNum = new AtomicLong();

    /**
     * 数字10000
     */
    private static final int NUM_10000 = 10000;

    /**
     * 私有构造器
     */
    private ThreadMsgHoldContext() {

    }

    /**
     * 
     * 功能描述: <br>
     * 〈功能详细描述〉
     * 
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static void put() {
        if (threadLocal != null) {
            String serialId = getNextSerialId();
            ThreadBean bean = new ThreadBean(serialId, null);
            threadLocal.set(bean);
        }
    }

    /**
     * 
     * 功能描述: <br>
     * 〈功能详细描述〉存放接口
     * 
     * @param interfaceId
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static void put(String interfaceId) {
        if (threadLocal != null) {
            String serialId = getNextSerialId();
            ThreadBean bean = new ThreadBean(serialId, interfaceId);
            threadLocal.set(bean);
        }
    }

    /**
     * 
     * 功能描述: <br>
     * 〈功能详细描述〉获取接口
     * 
     * @param serialId
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static String getInterfaceId() {
        if (threadLocal != null) {
            ThreadBean bean = threadLocal.get();
            if (bean != null) {
                return bean.getInterfaceId();
            }
        }
        return null;
    }

    private static String getNextSerialId() {
        String currentTime = String.valueOf(System.currentTimeMillis());
        Random random = new Random();
        int i = Math.abs(random.nextInt(NUM_10000));

        String randStr = String.format("%05d", i);
        long num = nextSerialNum.getAndIncrement();
        return currentTime + randStr + num;
    }

    /**
     * 
     * 功能描述: <br>
     * 〈功能详细描述〉
     * 
     * @param key
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static String get() {
        if (threadLocal != null) {
            ThreadBean bean = threadLocal.get();
            if (bean != null) {
                return bean.getSerialId();
            }
        }
        return null;
    }

    /**
     * 
     * 功能描述: <br>
     * 〈功能详细描述〉
     * 
     * @param key
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static void remove() {
        if (threadLocal != null) {
            threadLocal.remove();
        }
    }
}
